/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ifrr.gepro.util;

/**
 *
 * @author rafael
 */
//public class AuthorizationListener {
//    
//}
import br.ifrr.gepro.acesso.bean.UsuarioBean;
import br.ifrr.gepro.acesso.handler.SessaoMB;
import br.ifrr.gepro.acesso.handler.UsuarioMB;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class AuthorizationListener implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
        System.out.println("METODO DE VERIFICACAO DE ACESSO A PAGINA INICIANDO....");
        FacesContext facesContext = event.getFacesContext();
        try {
            String currentPage = facesContext.getViewRoot().getViewId();
            boolean isLoginPage = (currentPage.lastIndexOf(Navegacao.sufixoPaginaLogin) > -1);
            System.out.println(currentPage);

            SessaoMB usuario = (SessaoMB) JsfUtil.getMB("sessao");
            if (usuario != null) {
                UsuarioBean currentUser = usuario.getUsuario();
                if (!isLoginPage && currentUser.getUserlogin() == null) {
                    NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
                    nh.handleNavigation(facesContext, null, Navegacao.paginaLogin);
                }else{
                if (currentPage.contains("/ADM")) {
                if (!currentUser.getAcesso().equals("ADM")){
                    NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
                    nh.handleNavigation(facesContext, null, Navegacao.paginaLogin);
                }    
                }
                if (currentPage.contains("/TECNICO")) {
                if (!currentUser.getAcesso().equals("TEC")){
                    NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
                    nh.handleNavigation(facesContext, null, Navegacao.paginaLogin);
                }    
                }if (currentPage.contains("/CLIENTE")) {
                if (!currentUser.getAcesso().equals("CLI")){
                    NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
                    nh.handleNavigation(facesContext, null, Navegacao.paginaLogin);
                }    
                }
                
            }

        }} catch (Exception e) {
            NavigationHandler nh = facesContext.getApplication().getNavigationHandler();
            nh.handleNavigation(facesContext, null, Navegacao.paginaLogin);
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}
